package com.gxc.mall.base.aspect;

import com.gxc.mall.common.enums.JwtEnum;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @author GongXincheng
 * @since 2019-09-03 17:10
 */
@Aspect
@Component
public class ControllerAspect {

    private final Logger log = LoggerFactory.getLogger(ControllerAspect.class);

    @Pointcut("execution(* com.gxc.mall.*.controller.*.*(..))")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("Aspect in");

        HttpServletRequest request = getHttpServletRequest();
        String header = request.getHeader(JwtEnum.TOKEN_HEADER.getCode());
        System.out.println("header：" + header);
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            System.out.println(headerName + "：" + request.getHeader(headerName));
        }


        Object result = joinPoint.proceed();

        log.info("Aspect out");
        return result;
    }

    /**
     * 获取Request对象.
     */
    private HttpServletRequest getHttpServletRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            throw new RuntimeException("获取Request对象失败！");
        }
        return requestAttributes.getRequest();
    }

}


